﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Chire.ChireInter.Parent;
using Chire.ChireInter.Students;
using Chire.ChireInter.Teacher;
using Chire.ChireInter.Wechat;
using Chire.wechat;

namespace Chire.ChireInter.Identity
{
    public class Identity_Action
    {
        public enum AuthType
        {
            AuthType_None = 0,
            AuthType_Student = 3,
            AuthType_Parent = 1,
            AuthType_Teacher = 2,
        }

        #region 判断是否是炽热用户
        public bool hasChireUserMember(string code)
        {
            Identity_Model identityModel = authMainManager(code);

            bool hasMember = false;
            if (identityModel.student.id != null)
            {
                hasMember = true;
            }
            else if (identityModel.teacher.id != null)
            {
                hasMember = true;
            }
            else if (identityModel.parent.id != null)
            {
                hasMember = true;
            }

            return hasMember;
        }
        #endregion

        #region 2.获取当前的认证状态
        public Identity_Model authMainManager(string code)
        {
            Identity_Model identityModel = new Identity_Model();

            // 1. 根据code 获取
            Wechat_Action wechatAction = new Wechat_Action();
            string openid = wechatAction.getOpenIdWithCode(code);
            identityModel = getAuthType(openid);


            return identityModel;
        }
        #endregion

        #region 3.获取当前认证状态
        public Identity_Model getAuthType(string openid, AuthType authType)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select top 1 * from member_auth where openId = '" + openid + "' and auth_type = '" + (int)authType + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Identity_Model info = new Identity_Model();
            if (dr.Read())
            {
                info.code = dr["code"].ToString();
                info.is_auth = Convert.ToInt32(dr["is_auth"].ToString());
                info.auth_type = (int)authType;
                info.openId = openid;
                info.authtime =  dr["authtime"].ToString();
                info.datetime =  dr["datetime"].ToString();
               
            }
            sqlcon.Close();
            return info;
        }

        public Identity_Model getAuthType(string openid)
        {
            // 1.判断当前是否有认证
            Identity_Model IdentityModel = getAuthType_enum1(openid);
            if (IdentityModel.auth_type == (int)AuthType.AuthType_None || IdentityModel.auth_type == (int)AuthType.AuthType_Student) // 表示没有认证过或者是学生
            {         
                // 1. 判断是否有学生
                Student_Action studentAction = new Student_Action();
                Student_Model studentModel = studentAction.getStudentIdWithOpenId(openid);
                if (studentModel.id != null)
                {
                    IdentityModel.auth_type = (int)AuthType.AuthType_Student;
                    IdentityModel.is_auth = 0;
                    IdentityModel.student = studentModel;
                }
                else {
                    IdentityModel.auth_type = (int)AuthType.AuthType_None;
                }
            }
            else {                  // 表示已经认证过了
                if (IdentityModel.auth_type == (int)AuthType.AuthType_Parent) {
                    // 1. 根据父母的openId 获取绑定子女的openId
                    Parent_Action parentAction = new Parent_Action();
                    Student_Model studentModel = parentAction.getStudentIdWithBindingParentId(IdentityModel.openId);
                    IdentityModel.student = studentModel;
                }
                else if (IdentityModel.auth_type == (int)AuthType.AuthType_Teacher) {
                    Teacher_Action teacherAction = new Teacher_Action();
                    Teacher_Model teacherModel = teacherAction.getTeacherWithopenId(openid);
                    IdentityModel.teacher = teacherModel;
                    IdentityModel.auth_type = (int)AuthType.AuthType_Teacher;
                }
            }
            return IdentityModel;
        }

        public Identity_Model getAuthType_enum1(string openid)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select top 1 * from member_auth where openId = '" + openid + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Identity_Model info = new Identity_Model();
            if (dr.Read())
            {
                info.code = dr["code"].ToString();
                info.is_auth = Convert.ToInt32(dr["is_auth"].ToString());
                info.auth_type = Convert.ToInt32(dr["auth_type"].ToString());
                info.openId = openid;
                info.authtime = dr["authtime"].ToString();
                info.datetime = dr["datetime"].ToString();
            }
            sqlcon.Close();
            return info;
        }
        #endregion

        #region 4.进行绑定通知
        public int bindingNotice(string code, string auth_key,string transopenid)
        { 
            // 1. 根据code 获取openid
            Wechat_Action wechatAction = new Wechat_Action();
            string openId = "";
            if (transopenid.Length > 0)
            {
                openId = transopenid;
            }
            else {
                openId = wechatAction.getOpenIdWithCode(code);
            }

            // 2. 获取当前次数
            int times = bindingNoticeTimes(openId, auth_key);

            return times;
        }

        // 获取当前的次数
        public int bindingNoticeTimes(string openid ,string auth_key) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select times from wechat_auth_notice_times where openid = '"+openid+"' and auth_key ='"+auth_key+"'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            int times = 0;
            if (dr.Read())
            {
                times = Convert.ToInt32(dr["times"].ToString());
            }
            sqlcon.Close();
            return times;
        }

        // 次数增加+1
        public void bindingNoticeTimesUpdate(string openid, string auth_key) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strSqls = "update wechat_auth_notice_times set times = times + 1 where openid = '" + openid + "' and auth_key ='" + auth_key + "'";
            SqlCommand cmd = new SqlCommand(strSqls, sqlcon);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        // 插入
        public void bindingNoticeTimesInsert(string openid, string auth_key) {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
          
            StrInsert = "insert into wechat_auth_notice_times(openid,auth_key,times) values(@openid,@auth_key,@times)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 认证类型
            cmd.Parameters.Add("@openid", SqlDbType.VarChar, 50);
            cmd.Parameters["@openid"].Value = openid;
            // 2. 随机数
            cmd.Parameters.Add("@auth_key", SqlDbType.VarChar, 50);
            cmd.Parameters["@auth_key"].Value = auth_key;
            // 3. 认证openid
            cmd.Parameters.Add("@times", SqlDbType.Int);
            cmd.Parameters["@times"].Value = 1;
         

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        #endregion

        #region 通知方法
        // 1. 判断是否有code
        public string noticeManagerHasCode(string openId, string auth_type)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select top 1 * from member_auth where openId = '" + openId + "' and auth_type = '" + auth_type + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            string info = "";
            if (dr.Read())
            {
                info = dr["code"].ToString();
            }
            sqlcon.Close();
            return info;
        }

        // 2. 插入当前随机码
        public void insertRandomCode(string openId, string auth_type, string randomCode)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into member_auth(auth_type,code,openId,datetime,is_auth) values(@auth_type,@code,@openId,@datetime,@is_auth)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 认证类型
            cmd.Parameters.Add("@auth_type", SqlDbType.VarChar, 50);
            cmd.Parameters["@auth_type"].Value = auth_type;
            // 2. 随机数
            cmd.Parameters.Add("@code", SqlDbType.VarChar, 50);
            cmd.Parameters["@code"].Value = randomCode;
            // 3. 认证openid
            cmd.Parameters.Add("@openId", SqlDbType.VarChar, 50);
            cmd.Parameters["@openId"].Value = openId;
            // 4.认证时间
            cmd.Parameters.Add("@datetime", SqlDbType.VarChar, 100);
            cmd.Parameters["@datetime"].Value = DateTime.Now.ToString(); ;

            // 4.认证时间
            cmd.Parameters.Add("@is_auth", SqlDbType.VarChar, 100);
            cmd.Parameters["@is_auth"].Value = 0;
            
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }


        // 4. 进行推送 
        public void adminNoticeManager(string authCode,string authType,string openid,string name)
        {
            // 2. 拼接信息
            WechatModelDataList wechatModel = new WechatModelDataList();
            // 1.
            WechatModelData first = new WechatModelData();
            if(authType.Equals("1")){           // 家长推学生
                first.value = "【炽热教育】您有新的成员绑定，验证码为【" + authCode + "】";
            } else if(authType.Equals("2")){
                first.value = "【炽热教育】您有新的老师加入，验证码为【" + authCode + "】";
            }
            
            first.color = "#FF0000";

            // 2. 名字
            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = DateTime.Now.ToString();
            keyword2.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = "";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;

            list.remark = remark;
            Wechat_AccessToken token = new Wechat_AccessToken();
            token.memberTeacherAddInfo(openid, list);
        }
        
        #endregion

        #region 5. 进行绑定
        public void authBindingSuccess(string openid, string auth_type) {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update member_auth set is_auth = 1 , authtime = '" + DateTime.Now.ToString() + "'  where auth_type =" + auth_type + " and openId = '" + openid + "'";

            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
        }
        #endregion






        #region 微信 家长绑定成功后进行推送
        public void WechatParentBindingSuccessPushManager(string openId, string name)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = name + "家长您好！您已成功绑定" + name +"账号";
            first.color = "#6595A4";

            WechatModelData nameModel = new WechatModelData();
            nameModel.value = name;
            nameModel.color = "#6595A4";

            WechatModelData dateModel = new WechatModelData();
            dateModel.value = DateTime.Now.ToShortDateString();
            dateModel.color = "#6595A4";

            WechatModelData remark = new WechatModelData();
            remark.value = "绑定后，可以追踪学生到课情况，开课时间，作业情况，成绩曲线等。感谢您的使用。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = nameModel;
            list.keyword2 = dateModel;
            list.remark = remark;

            wechatToken.wechatBindingStudentInfo(openId, list);
        }
        #endregion

    }
}